<template>
  <a-modal :open="open" width="1100px" class="no-header-mark" :title="title" centered :keyboard="false" :footer="false" @cancel="onCancel">
    <div class="flex justify-between">
      <div class="w-1/2">
        <div class="flex justify-between">
          <BaseTitle title="基础信息" class="flex-1" />
          <div>
            <a-radio-group v-model:value="isReservation" button-style="solid" size="small" @change="reservationChange">
              <a-radio-button value="0">非预约</a-radio-button>
              <a-radio-button value="1">预约</a-radio-button>
            </a-radio-group>
          </div>
        </div>
        <div class="overflow-auto" :class="{ 'pr-2.5': leftHeight }" :style="{ height: leftHeight + 'px' }">
          <!-- <PatientInfoForm v-model:value="patientState" :patient-type="isReservation === '0' ? '患者' : '预约患者'" /> -->
        </div>
      </div>
      <div ref="rightRef" class="w-1/2 px-6">
        <BaseTitle title="挂号信息" />
        <a-form :model="registState" :label-col="{ style: { width: '100px' } }">
          <a-form-item name="czfz" label="就诊类别" class="w-full">
            <a-radio-group v-model:value="registState.czfz">
              <a-radio :value="0">初诊</a-radio>
              <a-radio :value="1">复诊</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="挂号类别" name="ghlb" class="w-full">
            <a-select v-model:value="registState.ghlb" class="w-full" :options="registTypeList" placeholder="请选择" @change="onSelectCategory" />
          </a-form-item>
          <a-form-item name="empName" label="专家医生" class="w-full">
            <SelectTable
              v-model:value="registState.empName"
              :search-params="{ ghlbid: registState.ghlb }"
              class="w-full"
              type="班制医生"
              @select="onSelectDoctor"
            />
          </a-form-item>
          <a-form-item v-if="!isArmy" label="挂号费别" class="w-full">
            <a-select v-model:value="category" :options="feeCategory" placeholder="请选择" @change="onSelectPrice" />
          </a-form-item>
          <a-form-item name="ksdm" label="挂号科室" :rules="[{ required: true, message: '挂号科室' }]" class="w-full" />
          <div class="px-16 pr-0 -mt-4 h-56 overflow-auto">
            <a-list :data-source="deptList" :class="registState.empName ? 'disabled-list' : ''">
              <template #renderItem="{ item }">
                <a-list-item :class="registState?.ksdms?.includes(item.value) ? 'active' : ''" @click="onSelectDept(item.value)">
                  {{ item.label }}
                </a-list-item>
              </template>
            </a-list>
          </div>
          <div v-if="!isArmy" class="flex items-end justify-end mt-6 mb-6 pr-5 text-orange-500">
            总费用：<span class="text-xl font-bold">￥{{ registerPrice }}</span>
          </div>
        </a-form>
      </div>
    </div>
    <a-space class="flex justify-end p-4">
      <a-button @click="onRest">重置</a-button>
      <a-button type="primary" @click="onOk">{{ isArmy || isMerge ? '保存' : '收费' }}</a-button>
      <!-- <a-button type="primary" @click="onClickPrice">挂号收费</a-button> -->
    </a-space>
    <ChargeModal v-model:open="chargeOpen" :register-price="registerPrice" @success="onSuccess" />
  </a-modal>
</template>
<script setup>
import { onMounted, ref, watch, nextTick } from 'vue'
import { message } from 'ant-design-vue'
import { post } from '@/utils/request'
import { formatAmount } from '@/utils/format.js'
import { getSystemConfig } from '@/utils/systemConfig'
import cofirmModal from '@/utils/confirm.js'
import ChargeModal from '@/components/ChargeModal'

const emit = defineEmits(['update:open', 'success'])
const props = defineProps({
  open: Boolean,
  title: {
    type: String,
    default: '新增数据'
  },
  department: {
    type: String,
    default: ''
  },
  rowData: {
    type: Object,
    default: () => ({})
  },
  isReservationState: {
    type: Boolean,
    default: false
  }
})
const patientState = ref({}) // 患者信息
const registState = ref({}) // 挂号信息
const deptList = ref([])
const registTypeList = ref([])
const feeCategory = ref([])
const category = ref('')
const chargeOpen = ref(false)
const isArmy = ref(false)
const isMerge = ref(false)
const registrationData = ref([])
const registerPrice = ref(0)
const priceTotal = ref(0)
const isReservation = ref('0')
const registrationItem = ref({})
const isStandard = ref(false)
const rightRef = ref(null)
const leftHeight = ref()
const isChargeMode = ref(1)
const isCategory = ref()
const isDepartment = ref()
const isPrint = ref()

const reservationChange = () => {
  patientState.value = {}
  registState.value.ghlb = registTypeList.value[0].value
  queryPriceTotal()
}
const onSelectCategory = (value) => {
  registState.value.ghlb = value
  if (registState.value.empName) {
    registState.value.empName = ''
  } else {
    queryPriceTotal()
  }
}

const onSelectDoctor = (select = {}) => {
  registState.value.empId = select.empId
  registState.value.empName = select.empName
  registState.value.ksdms = [select.ksdm]
  // queryPriceTotal(select)
  if (isChargeMode.value === '1') {
    if (Object.keys(select).length > 0) {
      feeCategory.value = [select]
      getDetailData(feeCategory.value)
    } else {
      queryPriceTotal(select)
    }
  } else if (isChargeMode.value === '2') {
    if (Object.keys(select).length > 0) {
      getDetailData()
    } else {
      queryPriceTotal(select)
    }
  }
}

const getDetailData = async (arr = []) => {
  if (arr.length > 0) {
    onChargePrice(arr)
  } else {
    const { data, code, msg } = await post('/operation/opex/getEmpGHFBRegistered', {
      empId: registState.value.empId,
      pageNum: 1,
      pageSize: 999
    })
    if (code !== 0) return message.error(msg || '请求失败')
    if (data.length > 0) {
      onChargePrice(data)
    } else {
      queryPriceTotal(arr[0])
    }
  }
}

const onChargePrice = (data) => {
  feeCategory.value = data?.map((item) => {
    return {
      label: item.ghfb,
      value: item.ghfybh
    }
  })
  category.value = data[0]?.ghfybh
  registrationItem.value = data[0]
  registrationData.value = data
  if (data.length > 0) {
    registerPrice.value = data[0].zfy ? formatAmount(data[0].zfy) : formatAmount(data[0].hjzje)
  } else {
    registerPrice.value = '0.00'
  }
  priceTotal.value = registerPrice.value
}

const queryPriceTotal = async (select = {}) => {
  const { code, data } = await post('/outp/oupCharge/getRegisterFee', {
    empId: select ? registState.value.empId : '',
    ghlbid: registState.value.ghlb
  })
  if (code !== 0) return
  if (data && data.length > 0) {
    onChargePrice(data)
  } else {
    registerPrice.value = '0.00'
    priceTotal.value = '0.00'
  }
}

const queryDeptTypeList = async () => {
  const { code, data } = await post('/outp/mzdj/getRegistrationTypeList')
  if (code !== 0) return
  registTypeList.value = data.map((item) => {
    return {
      label: item.ghlb,
      value: item.ghlbid
    }
  })
  queryPriceTotal()
}

const queryDeptList = async () => {
  // 获取科室
  const { code, data } = await post('/outp/mzdj/getDeptInfoList', {
    ksdm: '',
    pyjm: '',
    risbz: '',
    sfylks: '0'
  })
  registState.value.ksdms = props.department ? [props.department] : [isDepartment.value] || []
  if (code !== 0) return
  deptList.value = data.map((item) => {
    return {
      label: item.ksmc,
      value: item.ksdm
    }
  })
}
watch(
  () => registState.value.empName,
  (val) => {
    if (!val) {
      registStateEmpty()
    }
  }
)

watch(
  () => patientState.value.czfz,
  (val) => {
    if (val) {
      registState.value.czfz = val
    } else {
      registState.value.czfz = 0
    }
  }
)

watch(
  () => props.open,
  (val) => {
    if (val) {
      queryDeptList()
      queryDeptTypeList()
      registerPrice.value = '0.00'
      priceTotal.value = '0.00'
      isReservation.value = props.isReservationState ? '1' : '0'
      patientState.value = { ...props.rowData }
      registState.value = { czfz: 0, ghlb: isCategory.value || registTypeList.value[0].value }
      nextTick(() => {
        leftHeight.value = rightRef.value?.offsetHeight - 30
      })
    } else {
      patientState.value = {}
      registState.value = {}
    }
  }
)
const registStateEmpty = () => {
  registState.value.empId = ''
  registState.value.empName = ''
  registState.value.ksdms = []
  queryPriceTotal()
}
const onSelectDept = (select) => {
  if (isArmy.value) {
    if (registState.value.ksdms?.includes(select)) {
      registState.value.ksdms = registState.value.ksdms.filter((item) => item !== select)
      registerPrice.value = formatAmount(registState.value.ksdms.length ? registState.value.ksdms.length * +priceTotal.value : +priceTotal.value * 1)
    } else {
      registState.value.ksdms?.push(select)
      registerPrice.value = formatAmount(registState.value.ksdms.length ? registState.value.ksdms.length * +priceTotal.value : +priceTotal.value * 1)
    }
  } else {
    registState.value.ksdms = []
    registState.value.ksdms.push(select)
    registerPrice.value = formatAmount(registState.value.ksdms.length ? registState.value.ksdms.length * +priceTotal.value : +priceTotal.value * 1)
  }
}

const onCancel = () => {
  emit('update:open', false)
}

const onSelectPrice = (value) => {
  const item = registrationData.value.find((val) => val.ghfybh === value)
  registerPrice.value = item.zfy ? formatAmount(item.zfy) : formatAmount(item.hjzje)
  priceTotal.value = registerPrice.value
  registrationItem.value = item
}

const onSuccess = async (params) => {
  const res = await post('/common/patient/savePatientInfo', { ...patientState.value, jksy: 1 })
  if (res.code !== 0) {
    const isConfirm = await cofirmModal({ title: '提示', content: res.msg })
    if (isConfirm) {
      onSuccessPrice(params, res.data)
    }
  } else {
    onSuccessPrice(params, res.data)
  }
}

const onSuccessPrice = async (params = {}, brId = '') => {
  const { code, msg, jzbhs, pjhm } = await post(
    '/outp/mzdj/doRegister',
    {
      brId,
      ghlbid: registState.value.ghlb,
      ...patientState.value,
      ...registState.value,
      ...params,
      ...registrationItem.value
    },
    {
      loading: true
    }
  )
  if (code !== 0) return message.error(msg || '挂号失败')
  message.success('挂号成功')
  chargeOpen.value = false
  emit('success')
  onCancel()
  if (isMerge.value) {
    onPrint(jzbhs)
  } else {
    onPrint(jzbhs, pjhm)
  }
}
// 打印
const onPrint = (jzbhs = [], pjhm = []) => {
  if (jzbhs.length > 0) {
    jzbhs.forEach(async (item, index) => {
      const { code, msg, data } = await post(isPrint.value, { jzbh: item, pjhm: pjhm[index] || null, sftfbs: 0 })
      if (code !== 0) return message.error(msg)
      window.openExe?.rpt(data) //调用winform打印
    })
  }
}
const onRest = () => {
  patientState.value = {}
  registState.value = { ksdms: [], czfz: 0, ghlb: isCategory.value || registTypeList.value[0].value }
}
const onOk = async () => {
  const idCard = patientState.value.brSfz
  if (patientState.value.brZjlx && patientState.value.brZjlx === '身份证') {
    if (idCard && idCard.length) {
      const { code: codeZjh, msg: msgZjh } = await post('/common/util/getCsrq', { sfzhm: idCard })
      if (codeZjh !== 0) return message.error(msgZjh || '身份证有误')
    }
  }
  if (isArmy.value) {
    onSuccessPrice()
  } else {
    if (isMerge.value) {
      onSuccessPrice()
    } else {
      const isPass = getCheck()
      if (!registerPrice.value) {
        isPass && onSuccessPrice()
      } else {
        isPass && (chargeOpen.value = true)
      }
    }
  }
}
const getCheck = () => {
  if (!patientState.value.brName) {
    message.error('请填写患者信息')
    return false
  }
  if (patientState.value.isBrBlkh && !patientState.value.brBlkh) {
    return message.error('请填写病历号')
  }
  if (!registState.value.ksdms.length) {
    message.error('请选择挂号科室')
    return false
  }
  return true
}

onMounted(() => {
  isArmy.value = getSystemConfig('NAVYHIS_MODE') === '1' //军用系统
  isMerge.value = getSystemConfig('IS_MERGE_REGISTRATION_FEE') === '1' //是否合并挂号费
  isStandard.value = getSystemConfig('ENABLE_CHARGE_STANDARD_MODE') === '1' //收费标准
  isChargeMode.value = getSystemConfig('REGISTERED_FEE_MODEL') //挂号收费模式
  isCategory.value = getSystemConfig('REGISTER_DEFAULT_CATEGORY_CODE') //默认挂号类别编号
  isDepartment.value = getSystemConfig('REGISTER_DEFAULT_DEPT_CODE') //默认挂号科室编号
  isPrint.value = getSystemConfig('REGISTRATION_FORM_PRINT_MODE') === '2' ? '/outp/outPrint/getRegistrationPrint' : '/outp/outPrint/getRegistrationBillPrint' // 0：通用|1：上海黑马|2：茗视光
})
</script>
<style lang="less" scoped>
.disabled-list {
  :deep(.ant-list-item) {
    color: #00000070;
    background-color: #00000010;
    pointer-events: none;
  }
}
:deep(.ant-list-items) {
  display: flex;
  flex-wrap: wrap;
  .ant-list-item {
    justify-content: center;
    width: 100px;
    height: 40px;
    margin-top: 16px;
    margin-right: 32px;
    padding: 8px;
    background-color: var(--thin-color);
    border-radius: 6px;
    cursor: pointer;
    &:hover {
      background-color: var(--secondary-color);
    }
    &.active {
      color: #fff;
      // background-color: var(--secondary-color);
      background-color: var(--primary-color);
      // border: 2px solid var(--primary-color);
      // &:hover {
      //   background-color: var(--secondary-color);
      // }
    }
  }

  .ant-list-item:nth-child(3n) {
    margin-right: 0;
  }
}
:deep(.ant-col-14) {
  max-width: 83.33333333333334%;
}
</style>
